<?php

namespace App\Model;

use Hyperf\Database\Model\Model;

/**
 * 用户注销日志
 */
class UserCancelLog extends Model
{
    protected $table = 'user_cancellation_log';
    protected $fillable = [
        'user_id', 'flag'
    ];

    //注销中
    const FLAG_ING = 0;
    //已注销
    const FLAG_OK = 1;
    //已撤销注销
    const FLAG_FAIL = 2;

    /**
     * 添加记录
     */
    static function addRecord($userId = 0, $status = self::FLAG_ING)
    {
        return self::create([
            'user_id' => $userId, 'flag' => $status
        ]);
    }

    /**
     * 撤销注销
     */
    static function cancelApply($userId = 0)
    {
        $item = self::where(['user_id' => $userId])->orderBy('id', 'desc')->first();
        if (!$item) return false;
        return $item->update(['flag' => self::FLAG_FAIL]);
    }

    /**
     * 确认注销
     */
    static function confirmApply($userId = 0)
    {
        $item = self::where(['user_id' => $userId])->orderBy('id', 'desc')->first();
        if (!$item) return false;
        return $item->update(['flag' => self::FLAG_OK]);
    }

    /**
     * 当前获得更多
     */
    static function checkStatus($userId = 0)
    {
        $item = self::where(['user_id' => $userId])->orderBy('id', 'desc')->first();
        if (!$item || self::FLAG_FAIL == $item->flag) return ['status' => 0];
        elseif (self::FLAG_ING == $item->flag) return ['status' => -1, 'apply_time' => (string)$item->created_at];
        return ['status' => 2];
    }

    /**
     * 获取列表
     */
    static function getLogs($flag = -1, $startTime = '')
    {
        $where = [];
        $flag > -1 && $where[] = ['flag', $flag];
        $startTime && $where[] = ['created_at', '<=', $startTime];
        return array_unique(self::where($where)->pluck('user_id')->toArray());
    }
}
